<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Service;

use Doctrine\ORM\EntityManager;
use Sales\Entity\OrderDeliveryAddress;
use User\Entity\UserAddress;

class OrderDeliveryAddressManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加订单收货地址
     * @param array $data
     * @param $orderId
     * @return OrderDeliveryAddress
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addOrderDeliveryAddress(array $data, $orderId)
    {
        $addressInfo = $this->entityManager->getRepository(UserAddress::class)->findOneBy(['addressId' => $data['addressId']]);

        $deliveryAddress = new OrderDeliveryAddress();
        $deliveryAddress->valuesSet($addressInfo->valuesArray());
        $deliveryAddress->setOrderId($orderId);
        if(!empty($data['deliveryTimeInfo'])) $deliveryAddress->setDeliveryTimeInfo($data['deliveryTimeInfo']);

        $this->entityManager->persist($deliveryAddress);
        $this->entityManager->flush();

        return $deliveryAddress;
    }

    /**
     * 删除订单收货地址
     * @param $orderId
     * @return bool
     */
    public function deleteOrderDeliveryAddress($orderId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(OrderDeliveryAddress::class, 'd')->where('d.orderId = :orderId')->setParameter('orderId', $orderId);
        $qb->getQuery()->execute();

        return true;
    }
}